<?php
class Api_DbTable_Cart implements Core_Api_Manager_Plugin_Interface {
	protected $_session;
	protected $_api;
	
	public function __construct() {
		$this->_session = new Zend_Session_Namespace ( 'Api_Cart' );
		if (is_null ( $this->_session->cart ))
			$this->_session->cart = array ();
	}
	
	protected function _deleteProduct($id) {
		unset ( $this->_session->cart [$id] );
	}
	
	public function setProduct($id, $count) {
		$count = ( int ) $count;
		$id = ( int ) $id;
		if ($count == 0)
			return $this->_deleteProduct ( $id );
		$this->_session->cart [$id] = $count;
	}
	
	public function setProducts(array $data) {
		foreach ( $data as $id => $count )
			$this->setProduct ( $id, $count );
	}
	
	public function addProduct($id, $count) {
		$count = ( int ) $count;
		$id = ( int ) $id;
		if ($count === 0)
			return;
		if (! isset ( $this->_session->cart [$id] ))
			return $this->setProduct ( $id, $count );
		$this->_session->cart [$id] += $count;
	}
	
	public function addProducts(array $data) {
		foreach ( $data as $id => $count )
			$this->addProduct ( $id, $count );
	}
	
	public function getQuantity($product) {
		if ($product instanceof Api_Row_Product)
			$id = ( int ) $product->id;
		else
			$id = ( int ) $product;
		
		if (isset ( $this->_session->cart [$id] ))
			return ( int ) $this->_session->cart [$id];
		
		return 0;
	}
	
	public function getProducts() {
		return $this->_api->Product->find ( $this->_getProductsIds () );
	}
	
	protected function _getProductsIds() {
		$result = array ();
		
		foreach ( $this->_session->cart as $id => $quantity )
			$result [] = ( int ) $id;
		
		return $result;
	}
	
	public function clear() {
		unset ( $this->_session->cart );
	}
	
	public function getAmount() {
		$amount = 0;
		foreach ( $this->_session->cart as $count )
			$amount += $count;
		return $amount;
	}
	public function getAccount() {
		if ($this->getAmount () === 0)
			return 0;
		$sum = 0;
		$select = Zend_Db_Table::getDefaultAdapter ()->select ()->from ( 'prices', array ("id" => "product_id", "price" => Zend_Registry::get ( 'Core_User' )->getPriceScheme () ) )->where ( 'product_id in ' . '(' . implode ( ',', $this->_getProductsIds () ) . ')' );
		
		foreach ( $select->query ()->fetchAll () as $prod )
			$sum += ( float ) $prod ['price'] * $this->getQuantity ( $prod ['id'] );
		
		return $sum;
	}
	
	public function setManager(Application_Model_Manager $manager) {
		$this->_api = $manager;
	}
	public function getManager() {
		return $this->_api;
	}
}